package cac.common;/*
 *@program:test-curd
 *@description:产生鉴权参数
 *@author: lsl
 *@Time: 2022/9/23  15:22
 */
import com.google.common.hash.Hashing;
import sun.security.validator.ValidatorException;

import java.math.BigInteger;
import java.nio.charset.Charset;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.HashMap;
import java.util.Map;

public class GetAuthKey extends R {
    private  static String appId = "202101";
    private  static String appCode = "asrs";
    private  static String appKey = "ZmR1alNR";

    public static Map getKey(){
        long timestamp = System.currentTimeMillis();
        String timeStamp = String.valueOf(timestamp);
        String sysKey=Hashing.md5().hashString(appId+ appCode+appKey+timeStamp, Charset.forName("UTF-8")).toString();
        Map map = new HashMap();
        map.put("appId",appId);
        map.put("appCode",appCode);
        map.put("appKey",appKey);
        map.put("timeStamp",timeStamp);
        map.put("sysKey",sysKey);
        return map;
    }

    public static void  checkKey(Map map) throws ValidatorException {
        if (!map.get("appId").equals(appId)){
            throw new ValidatorException("appId不正确");
        }
        if (!map.get("appCode").equals(appCode)){
            throw new ValidatorException("appCode不正确");
        }
        if(!map.get("appKey").equals(appKey)){
            throw new ValidatorException("appKey不正确");
        }
        String sign = map.get("appId").toString()+map.get("appCode").toString()+map.get("appKey").toString()+map.get("timeStamp").toString();
        String signKey = md5(sign);
        if (!signKey.equals(map.get("sysKey"))){
            throw new ValidatorException("加密参数不正确");
        }
    }

    public static String md5(String plainText) {
        byte[] secretBytes = null;
        try {
            secretBytes = MessageDigest.getInstance("md5").digest(
                    plainText.getBytes());
        } catch (NoSuchAlgorithmException e) {
            throw new RuntimeException("没有md5这个算法！");
        }
        String md5code = new BigInteger(1, secretBytes).toString(16);// 16进制数字
        String tmpCode = md5code;
        // 如果生成数字未满32位，需要前面补0
        for (int i = 0; i < 32 - tmpCode.length(); i++) {
            md5code = "0" + md5code;
        }
        return md5code;
    }


}
